package com.example.onlinereadingsystem.demos.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.onlinereadingsystem.demos.web.dto.common.BaseContext;
import com.example.onlinereadingsystem.demos.web.dto.domain.Bookshelf;
import com.example.onlinereadingsystem.demos.web.dto.domain.Chapter;
import com.example.onlinereadingsystem.demos.web.dto.domain.Comment;
import com.example.onlinereadingsystem.demos.web.dto.domain.Novel;
import com.example.onlinereadingsystem.demos.web.dto.request.*;
import com.example.onlinereadingsystem.demos.web.dto.vo.*;
import com.example.onlinereadingsystem.demos.web.mapper.CommentMapper;
import com.example.onlinereadingsystem.demos.web.service.*;
import com.example.onlinereadingsystem.demos.web.util.JwtTokenUtil;
import com.example.onlinereadingsystem.demos.web.util.Result;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 小说详情页接口
 * @Author ljm
 * @Date 2024/12/11
 */
@Service
public class NovelDetailServiceImpl implements NovelDetailService {
    @Autowired
    private NovelService novelService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private NovelKindService novelKindService;
    @Autowired
    private BookshelfService bookShelfService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommentMapper commentMapper;

    /**
     * @auther ljm
     * @create 2024/11/7
     * @describe 获取小说阅读详情
     */
    @Override
    public Result<NovelReadingDetailVo> getNovelReadingDetail(String id, String token) {
        Novel novelEntity = novelService.getById(id);
        LambdaQueryWrapper<Chapter> chapterLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chapterLambdaQueryWrapper.eq(Chapter::getNovelId, novelEntity.getId());
        String kindName = novelKindService.getById(novelEntity.getNovelKindId()).getKindName();
        List<Chapter> chapterList = chapterService.list(chapterLambdaQueryWrapper);
        chapterList = chapterList.stream().sorted(Comparator.comparing(Chapter::getChapterNum)).collect(Collectors.toList());
        NovelReadingDetailVo res = new NovelReadingDetailVo();
        BeanUtils.copyProperties(novelEntity, res);
        res.setKindName(kindName);
        res.setChapterList(chapterList);
        LambdaQueryWrapper<Bookshelf> queryWrapper = new LambdaQueryWrapper<>();
        // String userId = BaseContext.getThreadLocal();
        if (!Strings.isEmpty(token)) {
            try {
                String userId = JwtTokenUtil.parseJwt(token).get("userId").toString();
                queryWrapper.eq(Bookshelf::getNovelId, id)
                        .eq(Bookshelf::getUserId, userId);
                res.setIsInBookShelf(bookShelfService.list(queryWrapper).size() > 0);
            } catch (Exception e) {
                res.setIsInBookShelf(false);
            }
        } else {
            res.setIsInBookShelf(false);
        }
        return Result.OK(res);
    }

    /**
     * @auther ljm
     * @create 2024/11/12
     * @describe 加入书架接口
     */
    @Override
    public Result<Boolean> addNovel(AddNovelParam param) {
        param.setUserId(BaseContext.getId());
        Bookshelf bookshelf = new Bookshelf();
        BeanUtils.copyProperties(param, bookshelf);
        bookshelf.setCurrentChapterId(param.getChapterId());
        LambdaQueryWrapper<Chapter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Chapter::getNovelId, param.getNovelId());
        List<Chapter> list = chapterService.list(queryWrapper);
        Chapter item = chapterService.getById(param.getChapterId());
        list = list.stream().sorted(Comparator.comparing(Chapter::getChapterNum)).collect(Collectors.toList());
        int index = list.indexOf(item);
        bookshelf.setCurrentChapter(index + 1);
        return bookShelfService.save(bookshelf) ? Result.OK(true) : Result.error("加入书架失败");
    }

    /**
     * @auther ljm
     * @create 2024/11/12
     * @describe 移除书架接口
     */
    @Override
    public Result<Boolean> removeNovel(RemoveNovelParam param) {
        param.setUserId(BaseContext.getId());
        LambdaQueryWrapper<Bookshelf> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Bookshelf::getUserId, param.getUserId())
                .eq(Bookshelf::getNovelId, param.getNovelId());
        return bookShelfService.remove(queryWrapper) ? Result.OK(true) : Result.error("移除书架失败");
    }

    /**
     * @auther ljm
     * @create 2024/12/11
     * @describe 获取小说主评论接口
     */
    @Override
    public Result<GetNovelMainCommentsVo> getNovelMainComments(GetNovelMainCommentsParam param) {
        // 主评论列表
        param.setOffset((param.getPage() - 1) * param.getSize());
        List<GetNovelMainCommentsItemVo> mainComments = commentMapper.getMainComments(param);
        GetNovelMainCommentsVo res = new GetNovelMainCommentsVo();
        res.setList(mainComments);
        param.setOffset(param.getOffset() + param.getSize());
        res.setHasMore(commentMapper.getMainComments(param).size() > 0);
        return Result.OK(res);
    }

    /**
     * @auther ljm
     * @create 2024/12/11
     * @describe 获取小说子评论接口
     */
    @Override
    public Result<GetNovelChildCommentsVo> getNovelChildComments(GetNovelChildCommentsParam param) {
        param.setOffset((param.getPage() - 1) * param.getSize());
        List<GetNovelChildCommentsItemVo> childComments = commentMapper.getChildComments(param);
        for (GetNovelChildCommentsItemVo item : childComments) {
            if (!Strings.isEmpty(item.getToUserId())) {
                item.setToUsername(userService.getById(item.getToUserId()).getUsername());
            }
        }
        GetNovelChildCommentsVo res = new GetNovelChildCommentsVo();
        res.setList(childComments);
        param.setOffset(param.getOffset() + param.getSize());
        res.setHasMore(commentMapper.getChildComments(param).size() > 0);
        return Result.OK(res);
    }

    /**
     * @auther ljm
     * @create 2024/12/11
     * @describe 发表评论接口
     */
    @Override
    public Result<Boolean> saveComments(SaveCommentsParam param) {
        String userId = BaseContext.getId();
        if (!Strings.isEmpty(userId)) {
            Comment comment = new Comment();
            BeanUtils.copyProperties(param, comment);
            comment.setFromUserId(userId);
            return commentService.save(comment) ? Result.OK(true) : Result.error("发表评论失败");
        }
        return Result.error("未登录");
    }
}
